package com.smproject.config;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.Arrays;

/**
 * fastJson 配置信息
 * @author hu.liang
 * @Date 2019/1/11 0011
 */
@Configuration
public class MyFastJsonConfig {

    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        ValueFilter valueFilter = new ValueFilter() {
            @Override
            public Object process(Object o, String s, Object o1) {
                if(o1 instanceof Date){
                    Date date = (Date)o1;
                    return DateUtil.format(date,"yyyy-MM-dd HH:mm:ss");
                }else if(o1 instanceof Timestamp){
                    Timestamp timestamp = (Timestamp) o1;
                    return DateUtil.format(timestamp,"yyyy-MM-dd HH:mm:ss");
                }
                return o1;
            }
        };
        fastJsonConfig.setSerializeFilters(valueFilter);
        converter.setFastJsonConfig(fastJsonConfig);
        return converter;
    }

    /**
     * 过滤器
     * @param characterEncodingFilter
     * @return
     */
    @Bean
    public FilterRegistrationBean characterEncodingFilter(CharacterEncodingFilter characterEncodingFilter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        filterRegistrationBean.setFilter(characterEncodingFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        return filterRegistrationBean;
    }
}
